<?php
/*
 * 会员管理
 */
namespace Admin\Controller;
use Admin\Model\memberModel;
use Admin\Model\gradeModel;
use Admin\Model\orderModel;
use Admin\Model\areaModel;
use Mobile\Model\tmpmsgModel;


class MemberController extends BaseController {
    
    public $memberModel;
    public $gradeModel;
    public $grade_arr;
    public $html;
    public $v;
    public $registerModel;
    public $orderModel;
    public $areaModel;
    public $laiyuan = array(
        "sharelink" => "链接",
        "scanqrcode" => "扫码",
        "scangh" => "扫码关注",
        "subscribe" => "关注",
        "import" => "导入",
        "timeline" => "朋友圈",
        "singlemessage" => "单聊",
        "groupmessage" => "群聊",
        "admin" => "管理员更改",
        "baodan" => "后台报单"
    );
    
    public function __construct() {
        parent::__construct();
        $this->areaModel = new areaModel;
        $this->memberModel = new memberModel();
        $this->gradeModel = new gradeModel();
        $this->orderModel = new orderModel();
        $this->grade_arr = $this->_get_gradename(array(fangan_type=>1));//获取用户等级
        $this->registerModel = M('register');
        $this->assign('grade_arr',$this->grade_arr);
        $this->orderModel = new orderModel;
    }
    
   /*
    * 获取用户等级或聘级
    * $where 是 array  判断是聘级或等级
    */
    protected function _get_gradename($where){
        //$where = array();
        $grade_list = $this->gradeModel->getGradeList($where);
    
        $new_grade = array();
        foreach($grade_list as $k=>$v){
            $new_grade[$v['grade_id']] = $v['grade_name'];
        }
        return $new_grade;
    }
    
    

    protected function _get_member_where(){
        $arrow = array(
            "mobile",
            "nickname",
            "province",
            "groupid",
            "start_create_time",
            "end_create_time",
            "user_id",
            "grade_id",
            "vip"
        );//允许提交的数据
        $data = param_filter($_GET,$arrow,$must=NULL,$filter=true);//过滤数据
        
        $where = "1";
        //todo
        if(is_set($data,'mobile')){
            $where .= " AND mobile like '".$data['mobile']."%'";
        }
        if(is_set($data,'nickname')){
            $where .= " AND ((nickname like'%".$data['nickname']."%') OR (realname like'%".$data['nickname']."%'))";
        }
        if(is_set($data,'province')){
            $where .= " AND province='".$data['province']."'";
        }
        if(is_set($data,'groupid')){
            $where .= " AND groupid='".$data['groupid']."'";
        }
        if(is_set($data,'express')){
            $where .= " AND express='".$data['express']."'";
        }
        if(is_set($data,'user_id')){
            $where .= " AND uid='".$data['user_id']."'";
        }
        if(is_set($data,'grade_id')){
            $where .= " AND grade_id=".$data['grade_id'];
        }
        
        if(is_set($data,'vip')){
            $where .= " AND grade_id>=2";
        }
        
        if(is_set($data,'start_create_time')){
            $where .= " AND create_time>='".$data['start_create_time']."'";
        }
        if(is_set($data,'end_create_time')){
            $where .= " AND create_time<'".trim($data['end_create_time'])."'";
        }
        
        return $where;
    }
    
    /*
     * 计算代理数量,代理消费金额
     */
    protected function _jisuan_daili_count($uid){
        $a_uid = $b_uid = array();//一级代理的uid集合
        $a_daili = $b_daili = $c_daili = array();//集合
        $a_count = $b_count = $c_count = 0;
        
        //计算我的一级代理
        $where_a = array(
            'refer_uid' => $uid
        );
        $a_daili = $this->memberModel->where($where_a)->select();
        $a_count = $this->memberModel->where($where_a)->count();
        
        //计算我的二级代理
        if(!empty($a_daili)){
            foreach ($a_daili as $k=>$v){
                $a_uid[] = $v['uid'];
            }
            //计算二级代理
            $where_b = array(
                'refer_uid' => array(
                    "IN",$a_uid
                )
            );
            $b_daili = $this->memberModel->where($where_b)->select();//我的二级代理
            $b_count = $this->memberModel->where($where_b)->count();
            if(!empty($b_daili)){
                foreach ($b_daili as $kk=>$vv){
                    $b_uid[] = $vv['uid'];
                }
                //计算3级代理
                $where_c = array(
                    'refer_uid' => array(
                        "IN",$b_uid
                    )
                );
                $c_count = $this->memberModel->where($where_c)->count();
            }
        }
        
        $daili_count = array(
            '1' => $a_count,
            '2' => $b_count,
            '3' => $c_count
        );
        
        return $daili_count;
        
    }
    

    

    
    
    /*
     * 编辑用户资料ajax
     */
    public function edituserajax(){
        $uid = get('edit_uid');
        $where = array(
            'uid' => $uid
        );
        $userinfo = $this->memberModel->getMember($where);
        
        
        $allow = array(
            "realname","mobile","wechat_id","minamo","refer_uid","grade_id","first_wuzhe",
            "yingyezhizhao",'shipinliutong','user_province','user_city','user_county','user_address',
            "store_name",'shenfenzheng','kefu_mobile','kefu_qrcode','bzj_money','pxf_money','idcard'
        );
        $must = array(
//            'mobile','realname'
        );
        $data = param_filter($_POST, $allow,$must,false,true);
        if(empty($data)){
            return_json(1,'请填写必填字段');
        }
        
        if(empty($userinfo)){
            $add = true;
            $userinfo = array(
                'grade_id' => $data['grade_id']
            );
        }
        
        if(is_set($data, 'mobile')){
            //修改了手机号
            //查找是否已经存在该手机号
            $where_mobile = array(
                "mobile" => $data['mobile'],
                "uid" => array(
                    "neq",$uid
                )
            );
            $mobile_find = $this->memberModel->getMember($where_mobile);
            if($mobile_find){
                return_json(1,"当前手机号已经被其他用户占用,请更换");
            }
        }
        
        //更改用户的推荐人
        if(is_set($data, 'refer_uid') && $data['refer_uid']!=0){
            //查找他的推荐人信息
            $where_refer = array(
                "uid" => $data['refer_uid'],
            );

            $user_refer = $this->memberModel->getMember($where_refer);
            if(empty($user_refer)){
                return_json(1,"当前推荐人不存在,请检查");
            }
            
            //检查推荐人是否合法
            $m = M('member');
            $user_uid = $userinfo['uid'];
            $new_refer_uid = $data['refer_uid'];
            if($user_uid ==  $new_refer_uid){
                return_json(1,"推荐人不能是自己");
            }
            $top_refer_uid = $m->where('uid='.$new_refer_uid)->getField('refer_uid');
      
            while($new_refer_uid){
                $top_refer_uid = $m->where('uid='.$new_refer_uid)->getField('refer_uid');
                if($top_refer_uid == $user_uid){
                    return_json(1,"该推荐人是你的下级");
                }
                $new_refer_uid = $top_refer_uid;
            }
            
            $data['refer_openid'] = $user_refer['openid'];
            $data['refer_nickname'] = $user_refer['realname'] ? $user_refer['realname'] : $user_refer['nickname'];
            $data['refer_unionid'] = $user_refer['unionid'];
            $data['regfrom'] = "admin";
        }
        if($data['refer_uid']==0) {
            $data['refer_openid'] = '';
            $data['refer_nickname'] = '';
            $data['refer_unionid'] = '';
        }
        
        if($add) {
            $password = '123456';
            $data['password'] = md5($password.C('SALT'));
            $res = $this->memberModel->add($data);
            if($res) {
                return_json(0,'添加成功','','/admin/member/index');
            }
        }
        
        if(empty($data)){
            return_json(1,"你提交的资料无任何修改");
        }
        
        //更新数据
        $res = $this->memberModel->editMember($where, $data);
        if($res){
            //更新成功之后，写重要的信息变更记录/推荐人变更/聘级变更
            
            //如果推荐人变更
            if($data['refer_uid']!=$userinfo['refer_uid'] ){
                $c = M("actionlog");
                $change1['log_type'] = 3;
                $change1['action_username'] = $this->admininfo["username"];
                $change1['target_uid'] = $userinfo["uid"];
                $change1['target_username'] = $userinfo["realname"]?$userinfo["realname"]:$userinfo["nickname"];
                $change1['from_data'] = $userinfo["refer_uid"];
                $change1['to_data'] = $data["refer_uid"];
                $change1['create_time'] = date('Y-m-d H:i:s');
                $change1['content'] = "(手工调整)".$userinfo['refer_nickname']."->".$data['refer_nickname'];
                $c->data($change1)->add();
            }
            
            //如果等级变更
            
            if($data['grade_id']!=$userinfo['grade_id']){
                $c = M("actionlog");
                $change2['log_type'] = 1;
                $change2['action_username'] = $this->admininfo["username"];
                $change2['target_uid'] = $userinfo["uid"];
                $change2['target_username'] = $userinfo["realname"]?$userinfo["realname"]:$userinfo["nickname"];
                $change2['from_data'] = $userinfo["grade_id"];
                $change2['to_data'] = $data["grade_id"];
                $change2['create_time'] = date('Y-m-d H:i:s');
                $change2['content'] = "(手工调整)".$this->grade_arr[$userinfo['grade_id']]."->".$this->grade_arr[$data['grade_id']];
                $c->data($change2)->add();  
                if($c){
                    //发送模板消息，等级变更
                    $this->_shengjiMsg($userinfo,$userinfo["grade_id"],$data["grade_id"]);
                }
            }
            
          
            
            //如果手机号码变更
            if($data['mobile']!=$userinfo['mobile']){
                $c = M("actionlog");
                $change4['log_type'] = 5;
                $change4['action_username'] = $this->admininfo["username"];
                $change4['target_uid'] = $userinfo["uid"];
                $change4['target_username'] = $userinfo["realname"]?$userinfo["realname"]:$userinfo["nickname"];
                $change4['from_data'] = $userinfo["mobile"];
                $change4['to_data'] = $data["mobile"];
                $change4['content'] = "(手工调整)".$userinfo["mobile"]."->".$data["mobile"];
                $change4['create_time'] = date('Y-m-d H:i:s');
                $c->data($change4)->add();
            }
            
            return_json(0,"更改成功",'',"/admin/member/index?user_id=".$uid);
        }
        return_json(1,"你的提交无任何修改");
    }
    
    
    /*
     * 编辑会员资料
     */
    public function edituser(){
        $uid = get('edit_uid');
        $where = array(
            'uid' => $uid
        );
        $userinfo = $this->memberModel->getMember($where);
        
        if(empty($userinfo)){
            $this->error("当前用户不存在");exit;
        }  
        $this->assign('userinfo',$userinfo);
        $this->display();
        
    }
    
    
    /*
     * 
     */
    /*
     * 我的代理
     */
    public function daili(){

        $dj = get('dj',1);//等级
        $uid = get('daili_user_id');
        
        
        $page = get('p',1);
        
        $a_uid = $b_uid = array();//一级代理的uid集合
        $a_daili = $b_daili = $c_daili = array();//集合
        $a_count = $b_count = $c_count = 0;
        
        //计算我的一级代理
        $where_a = array(
            'refer_uid' => $uid
        );
        
        
        $a_count = $this->memberModel->where($where_a)->count();
        if($dj == 1){
            $a_daili = $this->memberModel->getMemberList($where_a,$page);
            $page = new \Think\Page($a_count, 25);//
        }else{
            $a_daili = $this->memberModel->where($where_a)->select();
        }
        
        
        
        
        //计算我的二级代理
        if(!empty($a_daili)){
            foreach ($a_daili as $k=>$v){
                $a_uid[] = $v['uid'];
            }
            //计算二级代理
            $where_b = array(
                'refer_uid' => array(
                    "IN",$a_uid
                )
            );
            
            
            $b_count = $this->memberModel->where($where_b)->count();
            if($dj == 2){
                $page = new \Think\Page($b_count, 25);//
                $b_daili = $this->memberModel->getMemberList($where_b,$page);//我的二级代理
            }else{
                $b_daili = $this->memberModel->where($where_b)->select();//我的二级代理
            }
            
            
           
            if(!empty($b_daili)){
                foreach ($b_daili as $kk=>$vv){
                    $b_uid[] = $vv['uid'];
                }
                //计算3级代理
                $where_c = array(
                    'refer_uid' => array(
                        "IN",$b_uid
                    )
                );
                
                
                $c_count = $this->memberModel->where($where_c)->count();
                if($dj == 3){
                    $page = new \Think\Page($c_count, 25);//
                    $c_daili = $this->memberModel->getMemberList($where_c,$page);//我的二级代理
                }else{
                    $c_daili = $this->memberModel->where($where_c)->select();//我的3级代理
                }
                
                
            }
        }
        
        $daili_count = array(
            '1' => $a_count,
            '2' => $b_count,
            '3' => $c_count
        );
        $this->assign('daili_count',$daili_count);
        
        
        if($dj == 1){
            $datalist = $a_daili;
        }else if($dj == 2){
            $datalist = $b_daili;
        }else if($dj == 3){
            $datalist = $c_daili;
        }
        
        
        foreach ($datalist as $k=>$v){
            
            $datalist[$k]['daili_count'] = $this->_jisuan_daili_count($v['uid']);
            $datalist[$k]['grade_name'] = $this->_mygrade($v);//获取用户等级
            $datalist[$k]['laiyuan'] = $this->laiyuan[$v['regfrom']] ? $this->laiyuan[$v['regfrom']] : "未知";
        }
        
        $this->assign('datalist',$datalist);
       
        
        
        $show = $page->show3();
        $this->assign('page', $show);
        
        $this->display('index');
    }
    
    
    /*
     * 会员列表
     */
    public function index(){
        $page = get('p',1);
        $where = $this->_get_member_where();
        $grade = get('grade');
        if($grade){
            $where .= " AND grade_id ='".$grade."'";
            $this->assign('grade',$grade);
        }
        $mobile_check = get('mobile_check');
        if($mobile_check){
            if($mobile_check == 2){
                $mobile_check = 0;
            }
            $where .= " AND mobile_check ='".$mobile_check."'";
        }
        $member_list = $this->memberModel->getMemberList($where,$page);
        $start = date('Y-m-01 00:00:00');
        $end = date('Y-m-01 00:00:00', strtotime('+1 month'));
        foreach($member_list as $k=>$v){
            
            $member_list[$k]['grade_name'] = $this->_mygrade($v);//获取用户等级
            $member_list[$k]['laiyuan'] = $this->laiyuan[$v['regfrom']] ? $this->laiyuan[$v['regfrom']] : "未知";
//            $member_list[$k]['xiaoshou_nums'] = $this->_jisuanxiaoliang($v['uid']);//销售的箱数
//            $where1 = array(
//                'grade_id' => array('egt',5),
//                'refer_uid' => $v['uid']
//            );
//            $member_list[$k]['zhitui'] = $this->memberModel->where($where1)->count();//销售的箱数
            $time = strtotime(date('Y-m-01'));
            $start = date('Y-m-d 00:00:00', strtotime('+0 month',$time));
            $end = date('Y-m-d 00:00:00', strtotime('+1 month',$time));
            $member_list[$k]['mymoney'] = _getMyMoney($v['uid']);
            $member_list[$k]['teammoney'] = _getTeamMoney($v['uid']);
            
            $member_list[$k]['monthxiaofei'] = _getMyMoney($v['uid'],$start,$end);
            
            $member_list[$k]['refermoney'] = getReferMoney($v['uid']);
            
//            $member_list[$k]['month_mymoney'] = $this->_getMyMoney($v['uid'],$start,$end);
//            $member_list[$k]['month_teammoney'] = $this->_getTeamMoney($v['uid'],$start,$end);
        }
        $member_count = $this->memberModel->getMemberCount($where);
        $this->assign('datalist',$member_list);
        $this->assign('count',$member_count);
        
        $all_count = $this->memberModel->count();

        $count = array(
            '0' => $all_count,
            '1' => $this->memberModel->where('grade_id=1')->count(),
            '2' => $this->memberModel->where('grade_id=2')->count(),
            '3' => $this->memberModel->where('grade_id=3')->count(),
            '4' => $this->memberModel->where('grade_id=4')->count(),
            '5' => $this->memberModel->where('grade_id=5')->count(),
            '6' => $this->memberModel->where('grade_id=6')->count(),
            '7' => $this->memberModel->where('grade_id=7')->count(),
            '8' => $this->memberModel->where('grade_id=8')->count()
        );
        $this->assign('count',$count);
        $page = new \Think\Page($member_count, 25);
        $show = $page->show3();
        $this->assign('page', $show);
        $this->display();
    }
    

    public function apply(){
        $page = get('p',1);
        $applyModel = M('apply');
        $areaModel = M('area');
      
        if(isset($_GET['status'])) {
            $where['status'] = $_GET['status'];
        }
        $datalist = $applyModel->order('id desc')->where($where)->page($page,25)->select();
        foreach($datalist as $k=>$v) {
            $datalist[$k]['area'] = $areaModel->where(array('area_id'=>$v['area_id']))->find();
            $datalist[$k]['member'] = $this->memberModel->where(array('uid'=>$v['uid']))->find();
        }
        $count = $applyModel->where($where)->count();
        $this->assign('datalist',$datalist);
        $this->assign('count',$count);

        $page = new \Think\Page($count, 25);
        $show = $page->show3();
        $this->assign('page', $show);
        
        $this->display();
    }
    
    public function shenheApply () {
        if(IS_AJAX) {
            $data = $_POST;
            $applyModel = M('apply');
            $areaModel = M('area');
            $apply = $applyModel->where(array('id'=>$data['id']))->find();
            if(!$apply || $apply['status']!=0) {
                return_json(1,'该申请已处理');
            }
            $save = array(
                'status' => $data['status'],
                'shenhe_time' => date('Y-m-d H:i:s'),
                'shenhe_username' => $this->admininfo['username'],
                'note' => $data['note']
            );
            $res = $applyModel->where(array('id'=>$data['id']))->save($save);
            if($res) {
                if($data['status']==1) {
                    $areaModel->where(array('area_id'=>$apply['area_id']))->setField('id_sale',1);
                    //处理代理分佣
                    $ordercallback = new \Mobile\Controller\OrdercallbackController(array('baodan'=>true));
                    $ordercallback->handelApply($apply);

                }
                return_json(0,'处理成功');
            }
            return_json(1,'处理失败');
        }
        
    }

    /*
     * 个人业绩
     * 包含自己补货和推下级的升级单金额
     */
    protected function _getMyMoney ($uid,$start='',$end='') {
        $where = array(
            'uid' => $uid,
            'checked' => array('in',array(1,2,5)),
            'order_type' => array('in',array(1,2))
        );
        if($start&&$end) {
            $where['pay_time'] = array('between',array($start,$end));
        }
        $all = $this->orderModel->where($where)->sum('order_cashmoney');
        return $all>0?$all:0;
    }

     /*
     * 团队补货和报单
     */
    protected function _getTeamMoney ($uid,$start='',$end='') {
        //$all = $this->_getMyMoney($uid,$start,$end);
        $all = 0;
        $xiajilist = $this->memberModel->where(array('refer_uid'=>$uid))->field('uid,refer_uid')->select();
        while(!empty($xiajilist)) {
            $uids = array();
            foreach ($xiajilist as $k=>$v) {
                $uids[] = $v['uid'];
                $all += $this->_getMyMoney($v['uid'],$start,$end);
            }
            $xiajilist = $this->memberModel->where(array('refer_uid'=>array('in',$uids)))->field('uid,refer_uid')->select();
        }
        return $all>0?$all:0;
    }


    
    public function memberpage(){
        $where = $this->_get_member_where();
        $page = get('p',1);
        
        $all = $this->memberModel->where($where)->count();//总数
        
        $page_num = ceil($all/5000);
        
        return_json(0,"正在努力计算总....",$page_num);

    }
    
    
    public function memberexcel(){
        
        set_time_limit(1000);
        
        $where = $this->_get_member_where();
        $page = get('p',1);
        
        $all = $this->memberModel->where($where)->count();//总数
        
        $page_num = ceil($all/5000);
        
        //计算总
        $member_list = $this->memberModel->where($where)->order('uid DESC')->page($page,5000)->select();
        

        $datastr = "";
        
        if(empty($member_list)){
            return_json(1,"数据为空");
        }
        
        foreach($member_list as $k=>$v){
            $member_list[$k]['grade_name'] = $this->_mygrade($v);//获取用户等级
            
            $datastr .= $member_list[$k]['uid'].",";//UID
            
            $datastr .= str_replace(array(",","'","\""),array("，","＂","＂"),$member_list[$k]['realname']?$member_list[$k]['realname']:$member_list[$k]['nickname']).",";//转义
            
            $datastr .= $member_list[$k]['mobile'].",";//手机
            
            $datastr .= $member_list[$k]['grade_name'].",";//UID
            
            $datastr .= str_replace(array(",","'","\""),array("，","＂","＂"),$member_list[$k]['refer_nickname']).",";//转义
            
            $datastr .= $member_list[$k]['refer_uid'].",";
            $datastr .= $member_list[$k]['tixian'].",";
            $datastr .= $member_list[$k]['money'].",";
            $datastr .= $member_list[$k]['score'].",";
            $datastr .= $member_list[$k]['bzj_money'].",";
            $datastr .= $member_list[$k]['pxf_money'].",";
            $datastr .= $member_list[$k]['stock']."\n";
        
        }
        

  //      $header = "用户ID,昵称,等级,上级昵称,上级ID,1级数量,2级数量,3级数量,消费金额,销售金额,已提佣金,可提佣金,微币,剩余支持面膜,是否关注,加入时间,来源\n";
        $header = "用户ID,昵称,手机,等级,上级昵称,上级ID,已提佣金,可提佣金,积分,保证金,培训费,库存\n";
        
        
        $this->excel($datastr,$header,$excel_name="第".$page."页-共".$page_num."页-用户信息-");
    }
    
    
    /*
     * 级别列表
     */
    public function grade(){
        
        $where = array();
        $grade_list = $this->gradeModel->getGradeList($where);
        $this->assign('datalist',$grade_list);
        
        $this->display();
    }
    
    /*
     * 会员等级
     */
    protected function _mygrade($userinfo){

        $grade = $this->grade_arr[$userinfo['grade_id']];

        return $grade;
    }
    

    /*
     * changelog 
     * 会员信息变更，重要操作日志
     */
    public function changelog(){
        

        $page = get("p",1);
        $type = 0;
        $where = 1;
        if($_GET["type"]){
           
            $type = $_GET["type"];
            $where .= " AND log_type=".$_GET["type"];
        }
        
        if(get('user_id')){
            $where .= " AND target_uid=".get('user_id');
        }
        if(get('nickname')){
            $where .= " AND ((target_username like '%".get('nickname')."%') OR (target_username like '%".get('nickname')."%'))";
        }
        
        
        if(get('mobile')){
            $where .= " AND mobile=".get('mobile');
        }
        
        
        $parm = "?user_id=".get('user_id')."&nickname=".get('nickname')."&p=".$page."&mobile=".get('mobile');
        $this->assign('parm',$parm);
        
        
        $c = M("actionlog");
        $per = 50;
        $logs = $c->where($where)->page($page,$per)->order("create_time desc")->select();
        $count = $c->where($where)->count();
        $this->assign('count',$count);
        
        $page = new \Think\Page($count, 50);
        $show = $page->show3();
        $this->assign('page', $show);
        $this->assign("logs",$logs);
        $this->assign('type', $type);
        $this->display();
    }
	


    
    
    public function memberweb(){
        
        $uid = get('uid');
       if($uid){
           $where = null;
           $memberinfo = $this->memberModel->where($where)->field("uid as id,refer_uid as pid,realname as name,grade_id")->select();
           
           foreach ($memberinfo as $k=>$v){
               $new[$v['id']] = $v;
           }
           
           $xiaji = genTree5($new);
           $res = $this->_getXiaJiByUid($uid,$xiaji);
           $html = $this->_handleHtml($res);
           $html = "<ul>".$html;
           $html.= "</ul>";
           $memberinfo = $this->memberModel->where("uid = '".$uid."'")->find();
           $this->assign("html",$html);
           $this->assign('memberinfo',$memberinfo);
       }else{
            $html = "请输入姓名查询网络图";
        }
        $this->display();
    }
    
    

    
    /*
     * 取出某个人的数据
     * 
     */
    protected function _getXiaJiByUid($uid,$xiaji){

        foreach ($xiaji as $k=>$v){

            if($k == $uid){
               
                $this->v = array($uid=>$v);
               
            }
            
            //递归查找
            if($v['son']){
                   $this->_getXiaJiByUid($uid,$v['son']);
            }
        }
        return $this->v;
    }
    
    
    /*
     * 组装html
     */
    protected function _handleHtml($arr){
        
        
        foreach($arr as $k=>$v){
          $grade = $this->grade_arr[$v['grade_id']];
          if($v['son']){
              $this->html .= "<li><span><i class='icon-minus-sign'></i>".$v['name'].'-'.$v['id'].'-'.$grade."</i></span><a  style='color:blue;' href='/admin/member/index?user_id=".$v['id']."' target='_blank'/>查看该用户</a><ul> ";
              $this->_handleHtml($v['son']);
              
          }else{
              
            
              $this->html .= "<li><span><i class='icon-leaf'></i>".$v['name'].'-'.$v['id'].'-'.$grade."</i></span><a  style='color:blue;' href='/admin/member/index?user_id=".$v['id']."' target='_blank'/>查看该用户</a></li>";
              
          }
           
        }
        $this->html .= "</ul></li>";
        return ($this->html);
        
    }
 
    
    /*
     * 模板消息
     * 手工调整升级
     */
    
    /*
     * 升级用户等级
     */
    protected function _shengji($userinfo,$old,$new){
    
        //升级member表用户等级
        $where = array(
            "uid" => $userinfo['uid']
        );
        $data = array(
            "grade_id" => $new,//更改等级2
        );
        $res = $this->memberModel->editMember($where, $data);
    
        //发送模板消息
        $this->_shengjiMsg($userinfo,$old,$new);
    
    }
    
    
    /*
     * 升级通知,模板消息
     *
     */
    protected function _shengjiMsg($userinfo,$old,$new){
    
        //发送升级模板消息
        //判断是否关注, 没关注就别发了
        if(!$userinfo['subscribe']){
            //return false;
            //TODO
        }
    
        //发送模板消息
        $msg = $this->_sendsjmsgtmp($userinfo,$old,$new);//拼接模板消息
    
        $msgttt = array(
            "uid" => $userinfo['uid'],
            "openid" => $userinfo['openid'],
            "nickname" => $userinfo['nickname'],
            "groupid" => -1,
            "content" => $msg,
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
    
        return true;
    }
    
    
    /*
     * 升级消息
     *
     */
    protected function _sendsjmsgtmp($userinfo,$old,$new){
    
        $grade_arr = $this->_get_gradename();
    
        $tmp_id = $this->tmpl['DENG_JI']['tmp_id'];
        $color = $this->tmpl['DENG_JI']['color'];
    
        $url = get_domain()."/mobile/user/grade/";
        $footer = $url = '';
        
        //$footer ='\\n'."点击查看详情...";
        $msg = array(
            "touser" => $userinfo['openid'],
            "template_id" => $tmp_id,//
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode("恭喜,你的等级已提升~".'\\n'),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($grade_arr[$old]),//原先等级
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode($grade_arr[$new]),//new等级
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
    
        return $msg = urldecode(json_encode($msg));
    }
    
    public function getpassword(){
        $uid = get('uid');
        if(!$uid){
            return_json(1,"链接有误");
        }
        
        
       $memberinfo = $this->memberModel->where(array('uid'=>$uid))->find();
       if(!$memberinfo['idcard']) {
           return_json(1,'请先设置身份证号');
       }

        //检查身份证
        $idcard = $memberinfo['idcard'];
        $len = strlen($idcard);
        if($len != 18){
            return_json(1,"身份证号码填写错误,请重新填写身份证");
        }
        
        $pass = substr($idcard, -6);
        
        $init = md5($pass.C('SALT'));
        
        $this->memberModel->where(array('uid'=>$uid))->setField('password',$init);
        return_json(0,"重置成功");
    }
    
    public function getpaypassword(){
        $uid = get('uid');
        if(!$uid){
            return_json(1,"链接有误");
        }
        $new = md5('123456');
        $this->memberModel->where(array('uid'=>$uid))->setField('pay_password',$new);
        return_json(0,"重置成功,新支付密码为123456");
    }


     /*
     * 计算销量
     */
    protected function _jisuanxiaoliang($uid){
    
        //计算我自身的购买量
        $my_goumai = $this->memberModel->field("uid,refer_uid,jinhuo_nums")->where(array("uid"=>$uid))->find();
        if(!$my_goumai){
            return false;
        }
        //$jinhuo = $my_goumai['jinhuo_nums'];
    
        $jinhuo = 0;//不包括自己的进货量
         
        //计算销量
        $where_xiaji = array(
            "refer_uid" => $uid
        );
        $xiaji = $this->memberModel->where($where_xiaji)->field("uid,refer_uid")->select();
    
    
        while(!empty($xiaji)){
            //我有下级
            $jinhuo += $this->memberModel->where($where_xiaji)->sum("jinhuo_nums");
             
            $arr_uid = array();
            foreach ($xiaji as $k=>$v){
                $arr_uid[] = $v['uid'];
            }
            //计算县级代理
            $where_xiaji = array(
                'refer_uid' => array(
                    "IN",$arr_uid
                ),
            );
             
            $xiaji = $this->memberModel->where($where_xiaji)->field("uid,refer_uid")->select();
    
        }
    
        return $jinhuo ? $jinhuo : 0;
    }
    
    public function addmember () {
        $this->display('edituser');
    }
    
    public function upload() {
        $type = 'admin';
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     15145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =  "/";
        $upload->savePath  = "/upload/".$type."/";
        // 上传文件 
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        }else{// 上传成功
            return_json(0,'',$info['upfile']['savepath'].$info['upfile']['savename']);
        }
    }
    
     /*
     * 会员列表
     */
    public function registerlist(){
        $page = get('p',1);
        $where = $this->_get_member_where();
        $grade = get('grade');
        if($grade){
            $where .= " AND grade_id ='".$grade."'";
            $this->assign('grade',$grade);
        }
        $member_list = M('register')->where($where)->order('uid DESC')->page($page,20)->select();
        foreach($member_list as $k=>$v){
            $member_list[$k]['grade_name'] = $this->_mygrade($v);//获取用户等级
        }
        $this->assign('datalist',$member_list);
        $all_count = $this->registerModel->count();
        $this->assign('count',$all_count);
        $page = new \Think\Page($all_count, 25);
        $show = $page->show3();
        $this->assign('page', $show);
        $this->display();
    }
    
    public function editregister(){
        if(IS_AJAX) {
            $uid = get('edit_uid');
            $where = array(
                'uid' => $uid
            );
            $register = $this->registerModel->where($where)->find();
            $allow = array(
                "realname","mobile","wechat_id","minamo","refer_uid","grade_id","first_wuzhe",
                "yingyezhizhao",'shipinliutong','user_province','user_city','user_county','user_address',
                "store_name",'shenfenzheng'
            );
            $must = array(
                'mobile','realname'
            );
            $data = param_filter($_POST, $allow,$must,false,true);
            if(empty($data)){
                return_json(1,'请填写必填字段');
            }
            $member = $this->memberModel->where(array('mobile'=>$data['mobile']))->find();
            if($member) {
                return_json(1,'手机号已存在');
            }
            if(is_set($data, 'refer_uid') && $data['refer_uid']!=0){
                //查找他的推荐人信息
                $where_refer = array(
                    "uid" => $data['refer_uid'],
                );
                $user_refer = $this->memberModel->getMember($where_refer);
                if(empty($user_refer)){
                    return_json(1,"当前推荐人不存在,请检查");
                }
                
                if($user_refer['grade_id']<7) {
                    return_json(1,'门店不能作为推荐人');
                }
                if($user_refer['grade_id']<=$data['grade_id']) {
                    return_json(1,'推荐人等级必须大于用户');
                }
                $data['refer_openid'] = $user_refer['openid'];
                $data['refer_nickname'] = $user_refer['realname'] ? $user_refer['realname'] : $user_refer['nickname'];
                $data['refer_unionid'] = $user_refer['unionid'];
                $data['regfrom'] = "admin";
            }
            if($data['refer_uid']==0) {
                $data['refer_openid'] = '';
                $data['refer_nickname'] = '';
                $data['refer_unionid'] = '';
            }
            $data['password'] = md5('123456'.C('SALT'));
//            $data['pay_password'] = md5('123456');
            
            $data['openid'] = $register['openid'];
            $data['nickname'] = $register['nickname'];
            $data['headimgurl'] = $register['headimgurl'];
            $newid = $this->memberModel->add($data);
            $user = $this->memberModel->where(array('uid'=>$newid))->find();
            if($user) {
                $this->registerModel->where($where)->delete();
                $this->_newuserMsg($user, $user);
            }
            
            return_json(0,'审核成功,密码为手机号后8位倒序','','/admin/member/index');
        }
        $uid = get('edit_uid');
        $where = array(
            'uid' => $uid
        );
        $userinfo = $this->registerModel->where($where)->find();
        
        if(empty($userinfo)){
            $this->error("当前用户不存在");exit;
        }  
        
        $this->assign('userinfo',$userinfo);
        $this->display();
    }
    
    public function deleteregister () {
        $uid = get('edit_uid');
        $where = array(
            'uid' => $uid
        );
        $this->registerModel->where($where)->delete();
        return_json(0,'已删除','','/admin/member/registerlist');
    }
    
    
    protected function _newuserMsg($userinfo,$newuser){
        $tmp_id = $this->tmpl['NEW_USER']['tmp_id'];
        $content = '恭喜,您已通过审核';
        $footer ="现在可以登录系统使用了".'\\n\\n';
        $color = '#000';
        $url = '';
        $msg = array(
            "touser" => $userinfo['openid'],
            "template_id" => $tmp_id,
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode($content.'\\n'),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($newuser['realname']),
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode($newuser['mobile']),
                    'color' => $color,
                ),
                'keyword3' => array(
                    'value' => urlencode(date('Y-m-d H:i:s')),
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
        $msgttt = array(
            "uid" => $userinfo['uid'],
            "openid" => $userinfo['openid'],
            "nickname" => $userinfo['nickname'],
            "groupid" => -1,
            "content" => urldecode(json_encode($msg)),
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new \Mobile\Model\tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
        return true;
    }


    public function area () {
        if(IS_AJAX) {
            $data = $_POST;
            if(!$data['money']<0 || !is_numeric($data['money'])) {
                $data['money'] = 0;
            }
            $this->areaModel->where(array('area_id'=>$data['area_id']))->setField('money',$data['money']);
            return_json(0,'success');
        }
        $this->display();
    }

    public function getProvinceList () {
        $where = array(
            'level' => 1
        );
        $list = $this->areaModel->where($where)->select();
        foreach($list as $k=>$v) {
            $list[$k]['children'] = array();
        }
        return_json(0,'success',$list);
    }
    
    public function getProvinceChildren () {
        $area_id = get('area_id');
        $new = array();
        //$new[] = $this->areaModel->where(array('area_id'=>$area_id))->find();
        $where = array(
            'parentid' => $area_id,
            'level' => 2
        );
        $list = $this->areaModel->where($where)->select();

        foreach($list as $v) {
            if($v['is_zhixia']==0) {
                $new[] = $v;
            }
            $where = array(
                'parentid' => $v['area_id'],
                'level' => 3
            );
            $countys = $this->areaModel->where($where)->select();
            foreach($countys as $vv) {
                $vv['area_name'] = $v['area_name'].'-'.$vv['area_name'];
                $new[] = $vv;
            }
        }
        return_json(0,'success',$new);
    }

}